package com.yue.controller;

import com.yue.pojo.User;
import com.yue.pojo.Word;
import com.yue.service.UserService;
import com.yue.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private WordService wordService;
    @RequestMapping("/")
    public String hello(){
        return "index";
    }
    @PostMapping("/loginIn")
    public String loginIn(
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session,
            Model model){
        User user = userService.checkUser(username, password);
        if (user != null){
            session.setAttribute("user",user);
            User user1 = userService.checkUserAll(username, password);
            List<Word> words = user1.getWords();
            model.addAttribute("words",words);
            return "write";
        }else {
            return "login";
        }
    }
    @PostMapping("/login")
    public String login(
            @RequestParam String username,
            @RequestParam String password){
        userService.saveUser(username, password);
        return "redirect:/";
    }
    @PostMapping("/insertWord")
    public String insertWord(
            @RequestParam String word,
            HttpSession session,
            Model model
    ){
        Date date = new Date();
        Word word1 = new Word();
        word1.setWord(word);
        word1.setCreateDate(date);
        User user = (User) session.getAttribute("user");
        word1.setWid(user.getId());
        String wpassword = date.toString()+user.getId().toString();
        word1.setWpassword(wpassword);
        wordService.saveWord(word1);
        model.addAttribute("wpassword",wpassword);
        return "success";
    }
    @GetMapping("/get")
    public String get(){
        return "wget";
    }
    @PostMapping("/getWord")
    public String getWord(@RequestParam String wpassword,HttpSession session) {
        Word word = wordService.checkWord(wpassword);
        String word1 = word.getWord();
        session.setAttribute("word",word1);
        return "get";
    }

    @GetMapping("/yhjf")
    public String yhjf(HttpSession session){
        String word = (String) session.getAttribute("word");
        wordService.deleteWord(word);
        return "yhjf";
    }
}
